package com.cyf.wechat;

import com.cyf.wechat.network.bean.*;
import com.cyf.wechat.service.WechatRegService;
import com.cyf.wechat.service.WechatService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import java.io.IOException;

/**
 * Created by cage on 2016/9/4.
 */
@Controller
@RestController
//@CrossOrigin(allowedHeaders = "wechat.cheyifu2016.com")
@CrossOrigin
@Api("微信平台相关api")
public class WechatHttpController {

	private Logger logger = LoggerFactory.getLogger(this.getClass());

	@Autowired
	WechatRegService wechatRegService;
	@Autowired
	WechatService wechatService;

	@ApiOperation(value = "发送注册短信(新)")
	@PostMapping(value = "/wechat/sendRegSms")
	public WechatRegSmsRsp sendRegSms(@RequestBody WechatRegSmsReq req) {
		return wechatRegService.wechatRegisteSms(req);
	}

	@ApiOperation(value = "检查短信验证码(新)")
	@PostMapping(value = "/wechat/checkRegSms")
	public WechatCheckRegSmsRsp checkRegSms(@RequestBody WechatCheckRegSmsReq req) {
		return wechatRegService.checkRegSms(req);
	}

	// 2.微信用户查询是否注册过
	@ApiOperation(value = "微信用户查询是否注册过(新)")
	@PostMapping(value = "/wechat/user/query")
	public WechatUserRsp queryUser(@RequestBody WechatUserReq req) {
		return wechatRegService.wechatUserQuery(req);
	}

	@ApiOperation(value = "根据手机号查询注册车牌")
	@PostMapping(value = "/wechat/user/queryByMobile")
	public WechatQueryByMobileRsp queryUserByMobile(@RequestBody WechatQueryByMobileReq req) {
		return wechatRegService.queryUserByMobile(req);
	}

	@ApiOperation(value = "微信用户注册(新)")
	@PostMapping(value = "/wechat/user/registe")
	public WechatRegRsp registe(@RequestBody WechatRegReq req) {
		return wechatRegService.wechatRegiste(req);
	}

	@ApiOperation(value = "微信用户更新(新)")
	@PostMapping(value = "wechat/user/update")
	public WechatUserUpdateRsp updateUser(@RequestBody WechatUserUpdateReq req) {
		return wechatRegService.updateUserCar(req);
	}

	// 5.微信用户查询 自己已入场的车辆
	@ApiOperation(value = "(我要离场)微信用户查询自己已入场的车辆")
	@RequestMapping(value = "/wechatGetCars", method = RequestMethod.GET)
	public WechatGetCarsRsp getCarsService(
			@RequestParam(value = "openid") String openid) {
		WechatGetCarsReq req = new WechatGetCarsReq();
		WechatGetCarsRsp rsp;

		req.setOpenid(openid);

		rsp = wechatService.getInCars(req);

		return rsp;
	}

	// 6 微信用户获取金额
	/**
	 * 微信用户获取计费金额
	 * 
	 * @param plate
	 *            车牌号
	 * @param time
	 *            预计出场时间
	 * @return
	 */
	@ApiOperation(value = "微信用户获取计费金额")
	@RequestMapping(value = "/wechatGetFee", method = RequestMethod.GET)
	public WechatGetFeeRsp getFeeService(
			@RequestParam(value = "openid") String openid,
			@RequestParam(value = "plate") String plate,
			@RequestParam(value = "time") String time) {
		WechatGetFeeReq req = new WechatGetFeeReq();
		WechatGetFeeRsp rsp;

		req.setPlate(plate);
		req.setTime(time);
		req.setOpenid(openid);

		rsp = wechatService.getFee(req);

		return rsp;
	}

	/**
	 * 微信用户支付完成，向车场节点发送消息
	 * @param openid 微信用户唯一id
	 * @param plate		车牌号
	 * @param fee		支付费用（分）
	 * @param outTime	预计出场时间
	 * @param flag		自己支付，还是帮人支付
	 * @return
	 */
	@ApiOperation(value = "微信用户支付完成，向车场节点发送消息")
	@RequestMapping(value = "/wechatPayFee", method = RequestMethod.GET)
	public WechatPayFeeRsp payFeeService(
			@RequestParam(value = "openid") String openid,
			@RequestParam(value = "plate") String plate,
			@RequestParam(value = "fee") int fee,
			@RequestParam(value = "outTime") String outTime,
//			@RequestParam(value = "tradeNo") String tradeNo,
			@RequestParam(value = "orderNo") String orderNo,
			@RequestParam(value = "transactionId") String transactionId,
			@RequestParam(value = "flag") String flag,
			@RequestParam(value = "inParkingId") int inParkingId) {
		WechatPayFeeReq req = new WechatPayFeeReq();
		WechatPayFeeRsp rsp;

		req.setPlate(plate);
		req.setOpenid(openid);
		req.setFee(fee);
//		req.setTradeNo(tradeNo);
		req.setFlag(flag);
		req.setOutTime(outTime);
		req.setOrderNo(orderNo);
		req.setTransactionId(transactionId);
		req.setInParkingId(inParkingId);
		rsp = wechatService.payFee(req);

		return rsp;
	}

	/**
	 * 微信用户 行车记录查询
	 * 
	 * @param openid 微信用户唯一id
	 * @param inTime
	 * @param outTime
	 * @return
	 */
	@ApiOperation(value = "微信用户查询行车记录")
	@RequestMapping(value = "/inoutparking/query", method = RequestMethod.GET)
	public WechatInOutParkingRsp inOutParkingQueryService(
			@RequestParam(value = "openid") String openid,
			@RequestParam(value = "inTime") String inTime,
			@RequestParam(value = "outTime") String outTime,
			@RequestParam(value = "start") int start,
			@RequestParam(value = "end") int end,
			@RequestParam(value = "count",defaultValue = "-1") int count) {
		WechatInOutParkingReq req = new WechatInOutParkingReq();
		WechatInOutParkingRsp rsp;

		req.setOpenid(openid);
		req.setInTime(inTime);
		req.setOutTime(outTime);
		req.setStart(start);
		req.setEnd(end);
		req.setCount(count);

		rsp = wechatService.queryInOutParking(req);

		return rsp;
	}


	@ApiOperation(value = "微信用户查询行车记录")
	@RequestMapping(value = "/feedetail/query", method = RequestMethod.GET)
	public WechatQueryFeedetailRsp feedetailQuery(
			@RequestParam(value = "openid") String openid,
			@RequestParam(value = "start") int start,
			@RequestParam(value = "end") int end,
			@RequestParam(value = "count",defaultValue = "-1") int count) {
		WechatQueryFeedetailReq req = new WechatQueryFeedetailReq();

		req.setOpenid(openid);
		req.setStart(start);
		req.setEnd(end);
		req.setCount(count);

		return wechatService.queryFeedetail(req);

	}
	
	/**
	 * 获取微信用户月卡充值表单页面
	 * @param openid 微信用户唯一id
	 * @return
	 */
	@ApiOperation(value = "获取微信用户月卡充值表单页面")
	@RequestMapping(value = "/wechatGetFeeRate", method = RequestMethod.GET)
	public WechatGetFeeRateRsp getFeeRate(@RequestParam(value = "openid") String openid){
		WechatGetFeeRateReq req = new WechatGetFeeRateReq();

		req.setOpenid(openid);
		
		return wechatService.getFeeRate(req);
	}


	@ApiOperation(value = "获取微信用户月卡充值表单页面(新)")
	@PostMapping(value = "/wechat/wechatGetFeeRateNew")
	public WechatGetFeeRateNewRsp getFeeRateNew(@RequestBody WechatGetFeeRateReq req){
		return wechatService.getFeeRateNew(req);
	}

	/**
	 * 月卡充值 完成
	 * @param openid 微信用户唯一id
	 * @return
	 */
	@ApiOperation(value = "月卡充值完成")
	@RequestMapping(value = "/car/recharge", method = RequestMethod.GET)
	public void carRecharge(@RequestParam(value = "openid") String openid,
//			@RequestParam(value = "personId") int personId,
			@RequestParam(value = "plate") String plate,
			@RequestParam(value = "month") int month,
			@RequestParam(value = "fee") int fee,
			@RequestParam(value = "parkingId") int parkingId,
			@RequestParam(value = "orderNo") String orderNo,
			@RequestParam(value = "transactionId") String transactionId){
		WechatCarRechargeReq req = new WechatCarRechargeReq();
		
		req.setOpenid(openid);
//		req.setPersonId(personId);
		req.setMonth(month);
		req.setFee(fee);
		req.setPlate(plate);
		req.setParkingId(parkingId);
		req.setOrderNo(orderNo);
		req.setTransactionId(transactionId);
		
		wechatService.carRecharge(req);
	}

	/**
	 * 微信用户根据获取人管平台的部门员工的出入记录
	 * @param deptId 部门id
	 * @return	员工出入信息
	 */
	@ApiOperation(value = "获取人管平台的部门员工的出入记录")
	@RequestMapping(value = "/getEventRecord", method = RequestMethod.GET)
	public WechatEventRecordRsp getEventRecord(@RequestParam(value = "deptId") int deptId,
											   @RequestParam(value = "date", required = false) String date) {
		WechatEventRecordReq req = new WechatEventRecordReq();
		req.setDeptId(deptId);
		req.setDate(date);
		return wechatService.getEventRecord(req);
	}


	@ApiOperation(value = "受访者邀请访客")
	@PostMapping(value = "/wechat/visitor/invite")
	public WechatInviteRsp invite(@Valid @RequestBody WechatInviteReq req, BindingResult bindingResult) {
		if (bindingResult.hasErrors()) {
			return new WechatInviteRsp(WechatBusinessRsp.FAIL, bindingResult.getFieldError().getDefaultMessage());
		}
		return wechatService.invite(req);
	}

	@ApiOperation(value = "访客申请访问")
	@PostMapping(value = "/wechat/visitor/applyVisit")
	public WechatApplyVisitRsp applyVisit(@Valid @RequestBody WechatApplyVisitReq req, BindingResult bindingResult) {
		if (bindingResult.hasErrors()) {
			return new WechatApplyVisitRsp(WechatBusinessRsp.FAIL, bindingResult.getFieldError().getDefaultMessage());
		}
		return wechatService.applyVisit(req);
	}

	@ApiOperation(value = "被访客同意或拒绝访问")
	@PostMapping(value = "/wechat/visitor/processVisit")
	public WechatProcessVisitRsp processVisit(@Valid @RequestBody WechatProcessVisitReq req, BindingResult bindingResult) {
		if (bindingResult.hasErrors()) {
			return new WechatProcessVisitRsp(WechatBusinessRsp.FAIL, bindingResult.getFieldError().getDefaultMessage());
		}
		return wechatService.processVisit(req);
	}

	@ApiOperation(value = "根据订单id获取访客申请信息")
	@PostMapping(value = "/wechat/visitor/getVisitorRecord")
	public WechatGetVisitorRecordRsp getVisitorRecord(@RequestBody WechatGetVisitorRecordReq req, HttpServletRequest request) {
		return wechatService.getVisitorRecord(req);
	}

	@ApiOperation(value = "获取我的访客申请列表")
	@PostMapping(value = "/wechat/visitor/getMyApply")
	public WechatGetMyApplyRsp getMyApply(@Valid @RequestBody WechatGetMyApplyReq req, BindingResult bindingResult) {
		if (bindingResult.hasErrors()) {
			return new WechatGetMyApplyRsp(WechatBusinessRsp.FAIL, bindingResult.getFieldError().getDefaultMessage());
		}
		return wechatService.getMyApply(req);
	}

	@GetMapping(path = "/visitorImg/{imageId}")
	public void getVisitorImg(@PathVariable("imageId") Integer imageId, HttpServletResponse response) {
		byte[] imgData = wechatService.getVisitorImg(imageId);
		if (imgData != null && imgData.length > 0) {
			try {
				response.getOutputStream().write(imgData);
				response.flushBuffer();
			} catch (IOException e) {
				logger.error("访客记录获取图片异常：{}", e);
			}
		}
	}

	@ApiOperation("获取洗车券")
	@PostMapping(value = "/wechat/getCarWashCoupons")
	public WechatGetCarWashCouponsRsp getCarWashCoupons(@RequestBody WechatGetCarWashCouponsReq req) {
		return wechatService.getCarWashCoupons(req);
	}

	@ApiOperation("洗车")
	@PostMapping(value = "/wechat/carWash")
	public WechatCarWashRsp carWash(@RequestBody WechatCarWashReq req) {
		return wechatService.carWash(req);
	}
}
